import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Paths;

//must be singleton
public class Container {
    public  int total = 0;
    public static String DATA_DIR = "data";
    private static Integer CONTAINER_SIZE = 1 * 1024 * 1024;
    private byte[] buff = new byte[CONTAINER_SIZE];
    private int len = 0;
    public String name = String.valueOf(System.currentTimeMillis());
    public String mode = "local";
    public AzureClient azureClient = new AzureClient();

    private boolean enoughSpace(int chunkLen) {
        return CONTAINER_SIZE - len >= chunkLen;
    }
    public void flush(){
        total += 1;
        byte[] bytesToWrite = new byte[len];
        System.arraycopy(buff, 0, bytesToWrite, 0, len);

        try {
            File dataDirectory = Paths.get(DATA_DIR).toFile();
            if (!dataDirectory.isDirectory()) {
                dataDirectory.mkdir();
            }
            Files.write(Paths.get(DATA_DIR,name), bytesToWrite);
            if (mode.equals("azure")) {
                azureClient.upload(name, Paths.get(DATA_DIR,name).toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Chunk addChunk(byte[] bytes, int chunkLen) {
        if (!enoughSpace(chunkLen)) {
            flush();
            len = 0;
            name = String.valueOf(System.currentTimeMillis());
        }
        Chunk chunk = new Chunk(name, len, chunkLen);
        System.arraycopy(bytes, 0, buff, len, chunkLen);
        this.len += chunkLen;
        return chunk;
    }

    public  byte[] readChunkBytesFromContainer(Chunk chunk) {
        if (mode.equals("azure")) {
            azureClient.download(name, Paths.get(DATA_DIR,chunk.container).toString());
        }
        try (RandomAccessFile container = new RandomAccessFile(Paths.get(DATA_DIR,chunk.container).toFile(), "r")) {
            container.seek(chunk.offset);
            byte[] bytes = new byte[chunk.size];
            container.readFully(bytes);
            return bytes;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("readChunkBytesFromContainer wrong!");
        return null;
    }
}
